import { StyleSheet, View, ImageBackground, TouchableOpacity, Image, Text, FlatList } from 'react-native';
import { useTranslation } from 'react-i18next';
import React, { useState, useEffect, useMemo } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRoute } from '@react-navigation/native';
import { isIos, px2dp, scale } from '~/utils/px2dp';
import { FocusAwareStatusBar } from '~/components';
import { applyBloodDevice } from '~/utils/deviceMenues';
import { observer, deviceStore, userStore } from '~/store';
import HeartRateData from './components/HeartRateData';
import SportData from './components/SportData';
import BloodData from './components/BloodData';

export default observer(() => {
    const { t } = useTranslation();
    const insets = useSafeAreaInsets();
    const router: any = useRoute();
    const menueData = [
        { id: 1, title: t('HealthScreen.t3'), icon: require('~/assets/home/step.png') },
        { id: 2, title: t('HealthScreen.t1'), icon: require('~/assets/home/heart.png') },
        { id: 3, title: t('HealthScreen.t2'), icon: require('~/assets/home/blood.png') },
    ];
    const filteredData = menueData.filter((item) => {
        if (applyBloodDevice.includes(deviceInfo?.device_code) && item.id === 2) return false;
        if (!applyBloodDevice.includes(deviceInfo?.device_code) && item.id === 3) return false;
        if (
            !applyBloodDevice.includes(deviceInfo?.device_code) &&
            item.id === 2 &&
            deviceStore.device.connectedDeviceStatus !== 1
        )
            return false;
        return true;
    });
    const { params } = router;
    const initialSelected = params?.id ? params : menueData[0];
    const [selected, setSelected] = useState<any>(initialSelected);
    useEffect(() => {
        setSelected(params?.id ? params : menueData[0]);
    }, [params]);
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const { device, connectDeviceInfo } = deviceStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);

    const [open, setOpen] = useState(false);
    const handleSelect = (item) => {
        setSelected(item);
        setOpen(false);
    };

    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} barStyle={'light-content'} />
            <ImageBackground
                style={[styles.bg, { paddingTop: isIos() ? insets.top : insets.top + px2dp(32) }]}
                source={require('~/assets/login/bg4.png')}>
                <View style={styles.nav}>
                    <TouchableOpacity style={styles.dropdownHeader} onPress={() => setOpen(!open)} activeOpacity={0.7}>
                        <Image source={selected?.icon} style={styles.icon} />
                        <Text style={styles.headerText}>{selected?.title}</Text>
                        <Text style={styles.arrow}>{open ? '▲' : '▼'}</Text>
                    </TouchableOpacity>
                    {open && (
                        <View style={styles.dropdownList}>
                            <FlatList
                                data={filteredData}
                                keyExtractor={(item) => item.id.toString()}
                                renderItem={({ item }) => (
                                    <TouchableOpacity style={styles.dropdownItem} onPress={() => handleSelect(item)}>
                                        <Image source={item.icon} style={styles.icon} />
                                        <Text style={styles.itemText}>{item.title}</Text>
                                    </TouchableOpacity>
                                )}
                            />
                        </View>
                    )}
                </View>
                <View style={styles.contentStyle}>
                    {selected.id == 1 ? (
                        <SportData selectIndex={selected.id} />
                    ) : selected.id == 2 ? (
                        <HeartRateData selectIndex={selected.id} />
                    ) : (
                        <BloodData selectIndex={selected.id} />
                    )}
                </View>
            </ImageBackground>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    center: {
        justifyContent: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
    },
    bg: {
        flex: 1,
        resizeMode: 'contain',
        position: 'relative',
    },
    nav: {
        backgroundColor: 'rgba(255, 255, 255, 0.08)',
        borderRadius: px2dp(24),
        paddingHorizontal: px2dp(24),
        marginBottom: px2dp(24),
    },
    dropdownHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: px2dp(100),
    },
    headerText: {
        flex: 1,
        marginLeft: px2dp(16),
        color: '#fff',
        fontSize: scale(28),
    },
    arrow: {
        color: '#fff',
        fontSize: scale(28),
        marginLeft: px2dp(16),
    },
    dropdownList: {
        marginTop: px2dp(16),
        backgroundColor: 'rgba(255,255,255,0.15)',
        borderRadius: px2dp(24),
        overflow: 'hidden',
    },
    dropdownItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: px2dp(24),
        paddingHorizontal: px2dp(16),
    },
    itemText: {
        marginLeft: px2dp(16),
        color: '#fff',
        fontSize: scale(30),
    },
    icon: {
        width: px2dp(40),
        height: px2dp(40),
        resizeMode: 'contain',
    },
});
